#include "threadPool.h"

int recvfile(int sockfd, char* pathname){
    int flag = 1;
    int fd = open(pathname,O_RDWR|O_CREAT|O_APPEND,0666);
    off_t offset;
    off_t filesize;
    int cursize = 0;
    struct stat statbuf;
    fstat(fd,&statbuf);
    offset = statbuf.st_size - statbuf.st_size%4096;
    send(sockfd,&offset,sizeof(off_t),MSG_NOSIGNAL);
    recv(sockfd,&filesize,sizeof(off_t),0);
    ftruncate(fd, filesize);
    off_t mmap_size = filesize - offset;
    char *mp = (char *)mmap(NULL,mmap_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,offset);
//    recvn(sockfd,mp,mmap_size);
    
    while(cursize < mmap_size){
        sleep(1);
        ssize_t sret = recv(sockfd,mp + cursize, mmap_size - cursize,0);
        if(sret <= 0){
            printf("传输已断开!\n");
            ftruncate(fd, cursize + offset);
            munmap(mp,mmap_size);
            close(fd);
            flag = 0;
            printf("当前已接收 %5.2lf%%\n",(offset+cursize)*100.0/filesize);
            break;
        }
        cursize += sret;
        printf("正在接收..%5.2lf%%\r",(offset+cursize)*100.0/filesize);
        fflush(stdout);
    }
    if(flag){
        printf("100.00%%\n");
        munmap(mp,mmap_size);
        close(fd);
    }
    return 0;
}


